package com.cqc.jdk8.Jutil.concurrent;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Exchanger;
import java.util.jar.Manifest;

/**
 * @author cui
 * @date 2025/6/24 22:20
 * @description Exchanger 交换2个线程的值,且只能是2个线程。
 **/
public class ExchangerTest {

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(() -> {
            String oldVaLue = "A";
            System.out.println("threadName:" + Thread.currentThread().getName() + "交换前,value=" + oldVaLue);
            try {
                String newValue = exchanger.exchange(oldVaLue);
                System.out.println("threadName:" + Thread.currentThread().getName() + "交换后,value=" + newValue);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            String oldVaLue = "B";
            System.out.println("threadName:" + Thread.currentThread().getName() + "交换前,value=" + oldVaLue);
            try {
                String newValue = exchanger.exchange(oldVaLue);
                System.out.println("threadName:" + Thread.currentThread().getName() + "交换后,value=" + newValue);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
